package com.aia.prm.web;

import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.aia.prm.domain.VOFile;
import com.aia.prm.service.DefaultService;
import com.opensymphony.xwork2.ActionSupport;

public class DbImageAction extends ActionSupport {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(DbImageAction.class);

	private String id;
	private DefaultService defaultService;

	private long cacheTime = 3600 * 1000;
	/**
	 * Logger for this class
	 */

	private static final long serialVersionUID = 1L;

	public String execute() throws Exception {
		FileInputStream fis = null;

		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("image/png");
			response.setHeader("Cache-Control", "max-age=" + cacheTime / 1000);
			response.setDateHeader("Expires", System.currentTimeMillis() + cacheTime);
			response.setHeader("Pragma", "cache"); // Required to apply
			// caching in some
			// Tomcats

			// response.setHeader("cache", "no-cache");
			OutputStream os = response.getOutputStream();
			VOFile image = defaultService.getVOFile(id);

			if (image != null && image.getF_BIN() != null && image.getF_BIN().length > 0) {
				byte[] imgBin = image.getF_BIN();
				os.write(imgBin);
			} else {
				String str = ServletActionContext.getServletContext().getRealPath("/images/image.jpg");
				fis = new FileInputStream(str);
				IOUtils.copy(fis, os);
			}
			os.flush();
			os.close();
		} catch (javax.imageio.IIOException iioe) {
			if (logger.isDebugEnabled()) {
				logger.debug("IIOException"); //$NON-NLS-1$
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DbImageAction error:", e);
			throw new RuntimeException(e);
		}
		return null;
	}

	public DefaultService getDefaultService() {
		return defaultService;
	}

	public void setDefaultService(DefaultService defaultService) {
		this.defaultService = defaultService;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}
